// Package common @Title 图片公共处理方法
package common

import (
	"encoding/base64"
	"errors"
	"io"
	"os"
	"strings"
	"time"
)

// SaveBase64Pic 保存Base64图片
func SaveBase64Pic(photo string) (path, fileName string, err error) {
	i := strings.Index(photo, ",") // 从,后开始截取
	if i < 0 {
		err = errors.New("base64 err")
		return
	}

	heard := photo[:i+1]
	start := strings.Index(heard, "/")
	if start < 0 {
		err = errors.New("base64 ext err")
		return
	}
	end := strings.Index(heard, ";")
	if end < 0 {
		err = errors.New("base64 ext err")
		return
	}

	ext := heard[start+1 : end]
	fileDir := "./tmp/" + time.Now().Format("200601") + "/" // 文件存储路径
	err = IsNotExistMkDir(fileDir)
	if err != nil {
		return
	}

	dec := base64.NewDecoder(base64.StdEncoding, strings.NewReader(strings.TrimSpace(photo[i+1:]))) // 获取文件base64
	fileName = GetRandomString(16) + "." + ext                                                      // 文件名称
	path = fileDir + fileName                                                                       // 完整文件路径
	pic, err := os.Create(path)
	if err != nil {
		return
	}

	_, err = io.Copy(pic, dec)
	if err != nil {
		return
	}

	return
}
